package com.example.zdxk.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.zdxk.entity.Term;
import org.apache.commons.codec.binary.Base64;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;

public class UploadUtil {
    private static RestTemplate restTemplate = new RestTemplate();

    /**
     *  数据直接传给惠智灵杰
     * @param term
     */
    private static void upload(Term term)
    {
        String url = "http://10.210.5.21:9024/LocalService/ptlap/receive.action";
        JSONArray arr = new JSONArray();
        JSONObject postData = new JSONObject();
        postData.put("devImei", term.getterm_imei());
        postData.put("locType", term.getlocation_type()==8 ? "4" : String.valueOf(term.getlocation_type()));
        postData.put("lng", term.getlocation_lng());
        postData.put("lat", term.getlocation_lat());
        //发送base64编码的地名
        postData.put("locName", Base64.encodeBase64String(term.getlocation_name().getBytes()));
        if(term.getif_chain()==1)
            postData.put("chainState", String.valueOf(term.getchainstate()));
        else
            postData.put("chainState", "1");
        postData.put("batValue", String.valueOf(term.getbatvalue()));
        postData.put("repTime", term.getlocation_time());
        postData.put("spType", "6");
        arr.add(postData);
        JSONObject postDataArr = new JSONObject();
        postDataArr.put("data", arr);

        System.out.println(postDataArr.toJSONString());
        String str = HttpUtil.sendPost(url, postDataArr.toJSONString());

        System.out.println("resultstr:" + str);
    }

    /**
     *  数据传给转发器
     * @param term
     */
    public static void uploadToConverter(Term term){
//        String url = "http://114.115.129.128:35209/term/save";
//        String url = "http://222.240.80.67:35209/term/save";
        String url = "http://localhost:35209/term/save";
        System.out.println("时间： "+DateUtils.getTime());
        System.out.println("发送到转发器： "+term);

        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json");

        headers.setContentType(type);

        HttpEntity<Term> entity = new HttpEntity<Term>(term, headers);          //（对象， 头部）
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, entity, String.class);
        String result = responseEntity.getBody();
        System.out.println("转发result: "+result);

    }
}
